<template>
	<div>
		<input ref="uploadFile" type="file" @change="uploadFile" class="hidden">
		<button type="button" @click="selectFile" class="btn btn-white btn-info btn-round">
			<i class="ace-icon fa fa-upload"></i>
			{{text}}
		</button>

	</div>
</template>

<script>
export default{
	name: 'file',
	data() {
		return {
		}
	},
	props: {
		text: {
			default: '上传文件'
		},
		suffixs: Array,
		uploadUrl: String,
		purpose: Number,
		afterUpload: Function
	},
	methods: {
		uploadFile() {
			let file = this.$refs.uploadFile.files[0]
			if(!file) return
			let fileName = file.name
			let suffix = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length)
			console.log(fileName)
			let validSuffix = false
			this.suffixs.forEach(item=> {
				if(fileName.endsWith('.' + item)) {
					validSuffix = true
					return
				}
			})
			if(!validSuffix) {
				this.$toast("文件格式不正确,只支持文件格式:" + this.suffixs.join(','), this.$global.toast.warn)
				// 点击多次相同不合格文件都有提示
				this.$refs.uploadFile.value=null
				return
			}
			
			
			let formData = new window.FormData()
			formData.append('file', file)
			formData.append('purpose', this.purpose)
			formData.append('suffix', suffix)
			formData.append('name', fileName)
			this.$axios.post(this.uploadUrl, formData)
				.then(res => {
					if(res.data.status === 1) this.afterUpload(res.data)
					else this.$toast(this.text + "失败", this.$global.toast.fail)
				})
			this.$refs.uploadFile.value=null
		},
		selectFile() {
			// $('#uploadFile').trigger('click')
			this.$refs.uploadFile.click()
		}
	}
}
</script>

<style>
</style>
